<template>
  <el-dialog v-model="visible" :title="showTitle" width="50%" :before-close="cancelCilck">
    <el-form ref="deptFormRef" :model="DepartmentForm" :rules="DeptRules" label-width="130" style="max-width: 600px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="DepartmentForm.name" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="DepartmentForm.code" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="DepartmentForm.managerId" placeholder="请选择负责人" size="smill">
          <template v-for="item in managerList" :key="item.value">
            <el-option :label="item.username" :value="item.id" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="DepartmentForm.introduce" type="textarea" :rows="4" placeholder="1-100个字符" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelCilck">取消</el-button>
        <el-button type="primary" @click="btnOk"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, onMounted, nextTick, computed } from "vue";
import { getDepartmentLeaderListApi, getDepartmentListApi, addDepartmentApi, getDepartmentDetailApi, updateDepartmentApi } from "@/api/department";
import { type FormRules, type FormInstance, ElMessage } from "element-plus";
import type { IDepartmentForm } from "@/types";

onMounted(() => {
  getManagerList();
  getDepartmentList();
});

// 获取负责人列表
const managerList = ref([]); // 负责人列表

// a 定义表单数据结构
let DepartmentForm = reactive<IDepartmentForm>({
  code: "",
  introduce: "",
  managerId: "", // 负责人id
  name: "",
  pid: "", // 父级部门id 默认为0
});
// 控制对话框的显示与隐藏的属性
const visible = ref(false);

const showTitle = computed(() => {
  return DepartmentForm.id ? "编辑部门" : "新增部门";
});
// 校验部门编码是否重复的方法
const checkCokdeRepeat = async (rule: any, value: any, callback: any) => {
  // 添加校验部门编码是否重复的逻辑
  const res = await getDepartmentListApi();
  //判断是否是编辑场景 是多加一个判断条件 排除自身的编码重复情况:
  if (DepartmentForm.id) {
    // 编辑场景
    let checkRes = null;
    checkRes = res.filter((item) => item.id !== DepartmentForm.id);
    if (checkRes) {
      return callback();
    } else {
      return callback(new Error("部门编码不允许相同!"));
    }
  }
  // 添加校验部门编码是否重复的逻辑
  if (
    res.some((item) => {
      item.code === value;
    })
  ) {
    return callback(new Error("部门编码已存在!"));
  }
};
// 校验部门名称是否重复的方法
const checkNameRepeat = async (rule: any, value: any, callback: any) => {
  const res = await getDepartmentListApi();
  if (DepartmentForm.id) {
    // 编辑场景 排除自身
    let checkRes = null;
    checkRes = res.filter((item) => item.name !== DepartmentForm.name);
    if (checkRes) {
      return callback();
    } else {
      return callback(new Error("部门名称不允许相同!"));
    }
  }
  if (res.some((item) => item.name === value)) {
    return callback(new Error("部门名称已存在!"));
  } else {
    return callback();
  }
};
//接收父组件传来的数据
const props = defineProps({
  currentDeptId: {
    type: Number,
    default: null, // 对象/数组必须用函数返回
  },
});
// 定义事件监听器，用于触发父组件的方法
const emit = defineEmits(["updateDepartmentList"]);

//获取部门列表信息
const getDepartmentList = async () => {
  const res = await getDepartmentListApi();
  // console.log(res);
};

//获取负责人列表
const getManagerList = async () => {
  const res = await getDepartmentLeaderListApi();
  managerList.value = res;
};
// 获取部门详情信息
const getDepartmentDetail = async (currentDeptId: number) => {
  const res = await getDepartmentDetailApi(currentDeptId);
  // 将获取到的数据赋值给表单对象
  Object.assign(DepartmentForm, res);
  console.log(DepartmentForm);
};

//b 部门表单校验
const DeptRules: FormRules = {
  name: [
    {
      required: true,
      message: "请输入部门名称",
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "部门名称长度在 2 到 10 个字符",
      trigger: "blur",
    },
    {
      validator: checkNameRepeat,
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入部门编码",
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "部门编码长度在 2 到 10 个字符",
      trigger: "blur",
    },
    {
      validator: checkCokdeRepeat,
      trigger: "blur",
    },
  ],
  managerId: [
    {
      required: true,
      message: "请选择负责人",
      trigger: "change",
    },
  ],
  introduce: [
    {
      required: true,
      message: "请输入部门介绍",
      trigger: "blur",
    },
    {
      min: 1,
      max: 100,
      message: "部门介绍长度在 1 到 100 个字符",
      trigger: "blur",
    },
  ],
};
//c 表单实例引用
const deptFormRef = ref<FormInstance>();
// 提交表单的方法
const btnOk = () => {
  // 校验表单数据是否合法
  deptFormRef.value?.validate(async (valid) => {
    if (valid) {
      let msg = "新增";
      // 区分编辑和新增场景,提交表单数据
      if (DepartmentForm.id) {
        // 编辑场景
        msg = "编辑";
        //调用更新部门接口
        await updateDepartmentApi(DepartmentForm);
      } else {
        // 新增场景
        //将当前操作部门id赋值给表单的pid字段中，用于新增子部门时使用父级部门的id作为子部门的pid字段值
        DepartmentForm.pid = props.currentDeptId;
        //调用新增部门接口
        await addDepartmentApi(DepartmentForm);
      }

      // 重新加载部门列表
      emit("updateDepartmentList");
      // 提示用户操作成功
      ElMessage({
        type: "success",
        message: `${msg}部门成功!`,
      });
      // 关闭对话框
      cancelCilck();
    } else {
      ElMessage({
        type: "error",
        message: "表单验证失败",
        duration: 2000,
        showClose: true,
      });
    }
  });
};

// 关闭对话框的方法
const cancelCilck = () => {
  visible.value = false;
  //重置校验字段
  deptFormRef.value?.resetFields();
  //重置表单数据
  for (const key in DepartmentForm) {
    DepartmentForm[key] = "";
  }
};

// 暴露的属性和方法
defineExpose({
  visible,
  getDepartmentDetail,
});
</script>
<style lang="scss" scoped></style>
